<template>
  <div class="student">
    <section class="report-box">
      <el-row class="search-box">
        <el-col :span="24">
          <label for="" class="choose">
            <span> 级别：</span>
            <el-select v-model="grade" placeholder="请选择" size="small" @change="gradeChange" class="select-box">
              <el-option v-for="item in gradeList" :key="item.value" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </label>
          <label for="" class="choose">
            <span>班级：</span>
            <el-select v-model="classId" placeholder="请选择" size="small"  class="select-box">
              <el-option v-for="item in classList" :key="item.value" :label="item.label" :value="item.id"></el-option>
            </el-select>
          </label>
          <label for="" class="choose">
            <span>姓名：</span> <el-input v-model="name" class="select-box" size="small"></el-input>
          </label>
          <label for="" class="choose">
            <el-button icon="search" size="small" type="primary" @click="search">搜索</el-button>
          </label>
        </el-col>
      </el-row>
    </section>
    <div class="tip">
      <el-button icon="self-daoru" size="small" class="blue" @click="importInfo">导入</el-button>
      <el-button icon="self-daochu" class="blue" size="small" @click="exportData">导出</el-button>
      <el-button icon="document" class="blue" @click.native.prevent="goPage(1)" size="small">新增</el-button>
    </div>
    <div class="content">
      <el-table :data="dataList" ref="multipleTable" @selection-change="handleSelectionChange" tooltip-effect="dark" style="width: 100%">
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column prop="name" label="姓名"></el-table-column>
        <el-table-column prop="sex" label="性别" :formatter="sexFormat"></el-table-column>
        <el-table-column prop="idType" label="证件类型" :formatter="idTypeFormat"></el-table-column>
        <el-table-column prop="cardNo" label="证件号码"></el-table-column>
        <el-table-column prop="gradeYear" label="级别"></el-table-column>
        <el-table-column prop="className" label="班级"></el-table-column>
        <el-table-column prop="guardian" label="父/母姓名"></el-table-column>
        <el-table-column prop="mobile" label="联系电话"></el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <el-button @click.native.prevent="goPage(2, scope.row)" type="text" size="small"> 详情 </el-button>
            <el-button @click.native.prevent="goPage(3, scope.row)" type="text" size="small"> 编辑 </el-button>
            <el-button @click.native.prevent="deleteStudent(scope.row)" type="text" size="small"> 退学 </el-button>
          </template>  
        </el-table-column>        
      </el-table>
    </div>
    <div class="footer" v-if="dataList.length">
      已选{{selectList.length}}人&nbsp;&nbsp;&nbsp;&nbsp;
      <!-- <el-button type="primary">删除</el-button> -->
      <el-button class="color_b" size="small" @click="changeClass">调班</el-button>
      <!-- <el-button type="primary">分班</el-button> -->
    </div>
    <paginate :callback="getData" :page="pageObj"></paginate>
    <el-dialog title="选择级别与班级" :visible.sync="dialogFormVisible">
      <el-form :model="importObj">
        <el-form-item label="级别" label-width="200">
          <el-select v-model="importObj.grade" placeholder="请选择" size="small" @change="tmpGradeChange" class="select-box">
            <el-option v-for="item in tmpGradeList" :key="item.value" :label="item.label" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="班级" label-width="200">
          <el-select v-model="importObj.classId" placeholder="请选择" size="small"  class="select-box">
            <el-option v-for="item in tmpClassList" :key="item.value" :label="item.label" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <div label="" class="btn_tip">
          <upload :type="2" :successCallback="successCallback" :removeCallback="removeCallback" :httpAddress="httpAddress" :importObj="importObj"></upload>
          <el-button icon="self-daochu" size="small" class="blue" @click="exportTemplet">下载学生导入模板</el-button>
          <div class="tip_word">
            <div>温馨提示:</div>
            <div>
              <p>1.请按照学生导入模板要求正确填写学生信息</p>
              <p>2.请选择使用WPS或2007版及其以上版本Excel</p>
            </div>
          </div>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false">确 定</el-button>
      </div>
    </el-dialog>
    <el-dialog title="选择将要调往的级别与班级" :visible.sync="dialogShow">
      <el-form :model="changeObj">
        <el-form-item label="现在班级" label-width="100px">
          <!-- {{gradeName}} &nbsp;&nbsp;&nbsp;&nbsp; {{className}} -->
          <span v-for="(item, index) in selectGradeNameArr" :key="index">
            <el-tag type="primary">{{item}}</el-tag>&nbsp;&nbsp;
          </span>          
        </el-form-item>        
        <el-form-item label="调班学生" label-width="100px">
          <span v-for="item in selectList" :key="item.id">
            <el-tag type="primary" :closable="true"
            @close="handleClose(item.id)">{{item.name}}</el-tag>&nbsp;&nbsp;
          </span>
        </el-form-item>
        <el-form-item label="调往级别" label-width="100px">
          <el-select v-model="changeObj.grade" placeholder="请选择" size="small" @change="changeGradeChange" class="select-box">
            <el-option v-for="item in changeGradeList" :key="item.value" :label="item.label" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="调往班级" label-width="100px">
          <el-select v-model="changeObj.classId" placeholder="请选择" size="small"  class="select-box">
            <el-option v-for="item in changeClassList" :key="item.value" :label="item.label" :value="item.id"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogShow = false">取 消</el-button>
        <el-button type="primary" @click="changeClassGo">确 定</el-button>
      </div>
    </el-dialog>    
  </div>
</template>
<script>
import {getStudentsList, getClassList, changeStudent, dropOutStudent} from 'api/school/student/index'
import { sexFilter, idTypeFilter } from 'src/filter'
import upload from 'components/common/upload'
export default {
  data () {
    return {
      classId: '', // 选择年级
      grade: '', // 选择班级
      className: '', // 年级名字
      gradeName: '', // 班级名字
      name: '', // 搜索的名字
      selectList: '', // 选择数据
      pageObj: {
        currentCount: 1
      }, // 分页数据
      gradeList: [], // 所有年级级别
      classList: [], // 班级列表
      dataList: [], // 选择的学生列表
      httpAddress: '/net/schooladmin/school-student/import', // 导入文件的地址
      // httpAddress: 'https://jsonplaceholder.typicode.com/posts/', // 测试的导入文件的地址
      importObj: {
        grade: '',
        classId: ''
      }, // 导入文件的额外信息
      tmpGradeList: [], // 导入弹框的级别列表
      tmpClassList: [], // 导入弹框的班级列表
      dialogFormVisible: false, // 是否显示导入文件弹框
      changeObj: {
        grade: '',
        classId: ''
      }, // 导入文件的额外信息
      changeGradeList: [], // 调班的级别列表
      changeClassList: [], // 调班的班级列表
      dialogShow: false, // 是否显示调班弹框
      uploadSuccess: false, // 上传成功
      selectGradeNameArr: [] // 选中的学生级别,班级
    }
  },
  created () {
    this.init()
  },
  components: {
    upload
  },
  methods: {
    init () { // 初始化数据
      getClassList().then(v => {
        if (v.data.length) {
          // 导入文件时候的级别,班级信息
          this.tmpGradeList = JSON.parse(JSON.stringify(v.data))
          this.importObj.grade = v.data[v.data.length - 1].id
          this.tmpClassList = this.tmpGradeList[this.tmpGradeList.length - 1].children
          this.importObj.classId = this.tmpClassList[0].id
          // 调班的时候的级别,班级信息
          this.changeGradeList = JSON.parse(JSON.stringify(v.data))
          this.changeObj.grade = v.data[v.data.length - 1].id
          this.changeClassList = this.changeGradeList[this.changeGradeList.length - 1].children
          // 搜索的时候,年级班级信息
          this.gradeList = v.data
          this.gradeList.forEach(v => { // 查看一个年级的所有班级
            v.children.unshift({id: 0, label: '全部'})
          })
          this.grade = v.data[v.data.length - 1].id
          this.classList = v.data[v.data.length - 1].children
          this.classId = this.classList[0].id
          this.getData(1)
        }
      })
    },
    getData (int) { // 获取数据
      let obj = {
        gradeYear: this.grade,
        page: int,
        count: 15,
        name: this.name
      }
      if (parseInt(this.classId) !== 0) {
        obj.classId = [this.classId]
      }
      getStudentsList(obj).then(res => {
        this.dataList = res.data
        this.pageObj = res.page
      })
    },
    search () { // 搜索
      this.getData(1)
    },
    goPage (index, data) { // 路由跳转 1: 添加学生页面 2: 详情页面 3: 学生信息编辑页面
      switch (index) {
        case 1:
          this.$router.push({name: 'studentAdd'})
          break
        case 2:
          this.$router.push({name: 'studentDetail', query: {id: data.id}})
          break
        case 3:
          this.$router.push({name: 'studentEdit', query: {id: data.id}})
          break
      }
    },
    handleSelectionChange (val) { // 改变选中的学生
      this.selectList = val
      console.log(111)
    },
    gradeChange () { // 年级变化
      this.gradeList.forEach(v => {
        if (v.id === this.grade) {
          this.classList = v.children
          if (this.uploadSuccess) {
            this.classId = this.importObj.classId
            this.uploadSuccess = false
            this.getData(1)
          } else {
            this.classId = v.children[0].id
          }
        }
      })
    },
    tmpGradeChange (grade, classId) { // 导入班级学生信息年级变化
      this.importObj.grade = grade || this.importObj.grade
      this.tmpGradeList.forEach(v => {
        if (v.id === this.importObj.grade) {
          this.tmpClassList = v.children
          this.importObj.classId = classId || v.children[0].id
        }
      })
    },
    changeGradeChange () { // 调班弹窗年级变化
      this.changeGradeList.forEach(v => {
        if (v.id === this.changeObj.grade) {
          this.changeClassList = v.children
          this.changeObj.classId = v.children[0].id
        }
      })
    },
    deleteStudent (data) { // 学生退学
      this.$prompt('请输入退学原因', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        inputPattern: /\S/,
        inputErrorMessage: '退学原因不能为空'
      }).then(({ value }) => {
        dropOutStudent({id: data.id, remark: value}).then(v => {
          this.$message({
            type: 'success',
            message: '退学成功'
          })
          this.getData(1)
        })
      }).catch(() => {})
    },
    successCallback (response, file, fileList) { // 上传文件成功回调
      this.dialogFormVisible = false
      this.uploadSuccess = true
      this.$message({
        message: '上传成功!',
        type: 'success'
      })
      this.name = ''
      if (this.importObj.grade === this.grade) { // 上传成功改变搜索的框内容,由于级别一致,不会触发搜索级别框改变事件,需手动触发
        this.gradeChange()
      } else {
        this.grade = this.importObj.grade
      }
    },
    removeCallback (file, fileList) { // 上传成功的文件用户点击删除
      console.log(file, fileList)
    },
    sexFormat (row, col, value) { // 性别过滤器
      return sexFilter(value)
    },
    idTypeFormat (row, col, value) {
      return idTypeFilter(value)
    },
    exportData () { // 导出数据
      if (!this.dataList.length) {
        return this.$message({ message: '暂无数据,不支持导出', type: 'warning' })
      }
      let loginKey = window.localStorage.loginKey
      window.open(`/net/schooladmin/school-student/export?classId=${this.classId}&gradeYear=${this.grade}&name=${this.name}&login-key=${loginKey}`)
    },
    exportTemplet () { // 导出模板数据
      let loginKey = window.localStorage.loginKey
      window.open(`/net/schooladmin/school-student/down-templet?login-key=${loginKey}`)
    },
    changeClass () { // 调班按钮显示
      if (!this.selectList.length) {
        return this.$alert('请先选择学生', '提示', {
          confirmButtonText: '确定',
          callback: function () {}
        })
      }
      this.dialogShow = true
      this.selectGradeName()
    },
    importInfo () { // 导入学生信息显示
      this.tmpGradeChange(this.grade, this.classId)
      this.dialogFormVisible = true
    },
    changeClassGo () { // 调班
      let flag = true // 选中的班级跟要调往的班级是否一样
      if (!this.selectList.length) {
        return this.$alert('至少选中一个学生', '提示', {
          confirmButtonText: '确定',
          callback: function () {}
        })
      }
      if (!this.changeObj.classId) {
        return this.$alert('请选择班级', '提示', {
          confirmButtonText: '确定',
          callback: function () {}
        })
      }
      this.selectList.forEach(v => {
        if (this.changeObj.classId === v.classId) {
          flag = false
        }
      })
      if (!flag) {
        return this.$alert('调往班级必须与现所在所选的班级不同', '提示', {
          confirmButtonText: '确定',
          callback: function () {}
        })
      }
      changeStudent({
        ids: this.selectList.map(v => { return v.id }),
        newClassId: this.changeObj.classId
      }).then(res => {
        this.$router.go(0)
      })
    },
    handleClose (id) { // 删除选中的学生
      let tmp = {}
      this.selectList.forEach((v, i) => {
        if (v.id === id) {
          this.selectList.splice(i, 1)
        }
      })
      this.selectList = JSON.parse(JSON.stringify(this.selectList))
      this.selectList.forEach((v, i) => {
        tmp[v.id] = v
      })
      this.dataList.forEach(v => {
        if (tmp[v.id]) {
          this.$refs.multipleTable.toggleRowSelection(v, true)
        } else {
          this.$refs.multipleTable.toggleRowSelection(v, false)
        }
      })
      this.selectGradeName()
    },
    selectGradeName () {
      this.selectGradeNameArr = []
      this.selectList.forEach(v => {
        let tmpStr = v.gradeYear + '级' + v.className
        if (!this.selectGradeNameArr.includes(tmpStr)) {
          this.selectGradeNameArr.push(tmpStr)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
  .student {
    .color_b {
      color: #20a0ff;
    }
    padding: 20px;
    font-size: 14px;
    .search-box {
      padding: 25px 0 25px 25px;
      border: 1px solid #d3dce6;
      .choose {
        margin-right: 10px;
        .select-box {
          width: 120px;
        }
      }
    }
    .tip {
      margin: 20px;
      display: flex;
      justify-content: flex-end;
    }
    .footer {
      margin: 20px 0 20px 20px;
    }
    .btn_tip {
      position: relative;
      .blue {
        position: absolute;
        top: 0;
        left: 165px;
        height: 36px;
      }
    }
    .tip_word {
      margin-top: 10px;
      display: flex;
      color: #FF0000;
    }
  }
</style>